package com.qf.pojo.com.qf.dao.impl;
import com.qf.pojo.User;
import com.qf.pojo.com.qf.dao.UserDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
public class UserDaoImpl implements UserDao {
    @Override     //添加用户
    public void addUser(User inputUser) throws Exception {
        //1、加载核心配置文件SqlMapConfig.xml
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2、获取会话工厂对象SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3、获取会话对象SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4、执行指定的MapperStatement
        int insert = sqlSession.insert("test.addUser", inputUser);
        System.out.println(insert);
        //5、注意增删改操作一定要记得提交事务，数据库数据才会改变
        sqlSession.commit();
        sqlSession.close();//6、关闭会话
    }
    @Override     //添加用户并实现主键返回
    public void addUser2(User inputUser) throws Exception {
        //1、加载核心配置文件SqlMapConfig.xml
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2、获取会话工厂对象SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //3、获取会话对象SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //4、执行指定的MapperStatement
        int insert = sqlSession.insert("test.addUser2", inputUser);
        System.out.println(insert);
        sqlSession.commit();//5、提交事务
        sqlSession.close(); //6、关闭会话
    }
    @Override    //删除用户
    public void deleteUserById(int id) throws Exception {
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int i = sqlSession.delete("test.deleteUserById", id);
        System.out.println(i);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override   //修改用户
    public void updateUser(User inputUser) throws Exception {
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int i = sqlSession.update("test.updateUser", inputUser);
        System.out.println(i);
        sqlSession.commit();
        sqlSession.close();
    }
}
